<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Order\User;

use App\Api\Controllers\BaseController;
use App\Models\Store;
use App\Models\Stores;
use App\Param\User\UserParams;
use App\Services\Order\UserService;
use App\Services\PrintSqlService;
use App\Traits\ResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderQueryController extends BaseController
{

    use ResponseTrait;


    public function returnWhere(\stdClass $user, array $data): array
    {
//        $user = $this->parseToken();
        $user_id = $data["user_id"] ?? "";
        if ($user_id == "") {
            $user_id = $user->user_id;
        }
        if ($user_id == 101) {
            $stores = Stores::query()->where(array('ascription' => 1))->select('store_id')->get()->toArray();
            $store_ids = [];
            foreach ($stores as $key => $val) {
                $store_ids[$key] = $val['store_id'];
            }
            $user_ids = $this->getSubIds(1);
        } else if ($user_id == 747) {
            $stores = Stores::query()->where(array('ascription' => 4))->select('store_id')->get()->toArray();
            $store_ids = [];
            foreach ($stores as $key => $val) {
                $store_ids[$key] = $val['store_id'];
            }
            $user_ids = $this->getSubIds(1);
        } else if ($user_id == 874) {
            $stores = DB::table('stores')->where(array('ascription' => 5))->select('store_id')->get();
            $store_ids = [];
            foreach ($stores as $key => $val) {
                $store_ids[$key] = $val['store_id'];
            }
            $user_ids = $this->getSubIds(1);
        } else if ($user_id == 1002) {
            $stores = DB::table('stores')->where(array('ascription' => 6))->select('store_id')->get();
            $store_ids = [];
            foreach ($stores as $key => $val) {
                $store_ids[$key] = $val['store_id'];
            }
            $user_ids = $this->getSubIds(1);
        } else {
            $store_ids = [];
            $user_ids = $this->getSubIds($user_id); // 所有下级代理id
        }
        //处理总店和分店的关系
        if (!empty($data["store_id"])) {
            $storeIds = [$data["store_id"]];
            if (!empty($data["start_date"]) && date("Ymd", time()) != date("Ymd", strtotime($data["start_date"]))) {
                $store = Store::query()->where("store_id", $data["store_id"])->first();
                if (!empty($store)) {
                    if ($store->pid == 0) {
                        $storeP = Store::query()->where("pid", $store->id)->get()->toArray();
                        $storeIds = array_merge($storeIds, array_column($storeP, "store_id"));
                    }
                }
            }
        }
        $where = [
            "page" => empty($data["page"]) ? 1 : $data["page"],
            "pagesize" => empty($data["pagesize"]) ? 15 : $data["pagesize"],
            "user_id" => $user_ids,
            "store_id" => $storeIds ?? "",
            "store_ids" => $store_ids,
            "pay_status" => empty($data["pay_status"]) ? "" : $data["pay_status"],
            "company" => empty($data["company"]) ? "" : $data["company"],
            "start_date" => $data["start_date"] ?? "",//empty() ? date("Y-m-d", time()) . " 00:00:00" : $data["start_date"],//$request->input("start_date", date("Y-m-d", time()) . " 00:00:00"),
            "end_date" => $data["end_date"] ?? "",//empty() ? date("Y-m-d", time()) . " 23:59:59" : $data["end_date"],//$request->input("end_date", date("Y-m-d", time()) . " 23:59:59"),
            "total_amount" => empty($data["total_amount"]) ? "" : $data["total_amount"],//$request->input("total_amount", ""),
            "device_id" => empty($data["device_id"]) ? "" : $data["device_id"],//$request->input("device_id", ""),
            "out_trade_no" => empty($data["out_trade_no"]) ? "" : $data["out_trade_no"],//$request->input("out_trade_no", "")
            "trade_no" => empty($data["trade_no"]) ? "" : $data["trade_no"],
            "ways_source" => empty($data["ways_source"]) ? "" : $data["ways_source"],
            "qwx_no" => empty($data["qwx_no"]) ? "" : $data["qwx_no"],
            "auth_code" => empty($data["auth_code"]) ? "" : $data["auth_code"],

        ];
        if (empty($where["out_trade_no"])) {
            if (empty($where["start_date"])) {
                $where["start_date"] = date("Y-m-d", time()) . " 00:00:00";
            }
            if (empty($where["end_date"])) {
                $where["end_date"] = date("Y-m-d", time()) . " 23:59:59";
            }
            if (date("Ymd", strtotime($where["end_date"])) == date("Ymd", time()) && date("Ymd", strtotime($where["start_date"])) != date("Ymd", time())) {
                throw new \Exception("当天数据不能和历史数据一起查询");
            }
            if (date("Ym", strtotime($where["start_date"])) != date("Ym", strtotime($where["end_date"]))) {
                throw new \Exception("不能跨月查询");
            }
            if ($where["end_date"] < $where["start_date"]) {
                throw new \Exception("截止时间必须大于开始时间");
            }
        }
        if ($where["total_amount"] > 0 && $where["store_id"] == "") {
            throw new \Exception("按照金额来查询，必须传入店铺ID");
        }
        return $where;
    }

    public function orderQuery(Request $request): string
    {
        try {
            $data = $request->all();
            $user = $this->parseToken();
            $where = $this->returnWhere($user, $data);
            $service = new UserService();
            $result = $service->orderQuery($where);
            return $this->successResponse("ok", $result);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    public function orderQueryExport(Request $request): string
    {
        try {
            $data = $request->all();
            $user = $this->parseToken();
            $where = $this->returnWhere($user, $data);
            $service = new UserService();
            $res = $service->orderQueryExport($where);
            if (empty($res)) {
                return $this->errorResponse('导出失败！');
            }
            return $this->successResponse("ok",$res);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    public function orderNewQueryExport(Request $request): string
    {
        try {
            $data = $request->all();
            $user = $this->parseToken();
            $where = $this->returnWhere($user, $data);
            $service = new UserService();
            $res = $service->newOrderQueryExport($where,$user->user_id);
            return $this->successResponse("ok", $res);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }

    /**
     * 获取导出列表
     * @param Request $request
     * @return string
     */
    public function getOrderExportList(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $user = $this->parseToken();
        $uid = $user->user_id;
        $service = new UserService();
        $result = $service->getOrderExportListService($page,$pageSize,$where =['export_channel'=>1,'uid'=>$uid] );
        return $this->successResponse("ok", $result);
    }

    /**
     * 修改导出状态
     * @return string
     */
    public function OrderExportSaveExportStatus()
    {
        $params = UserParams::create();
        $UserService = new UserService();
        $result = $UserService->OrderExportSaveExportStatusService($params);
        if ($result)
            return $this->successResponse("ok");
        return $this->errorResponse('修改失败');
    }


}